package com.dmall.graph.cc;

import com.dmall.graph.base.Graph;
import com.dmall.graph.dfs.GraphDFS;

import java.util.ArrayList;

/**
 * @author xiao1.wang
 * @date 2022-06-16 09:52:07
 */
public class ConnectedComponent {
    private Graph G;
    private boolean[] visited;
    private int[] parent;
    private int cccount;

    public ConnectedComponent(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];
        parent = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            parent[i] = -1;
        }
        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                dfs(i, cccount);
                cccount++;
            }
        }
    }

    private void dfs(int v, int p) {
        visited[v] = true;
        parent[v] = p;
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w, p);
            }
        }
    }

    public int count() {
        return cccount;
    }

    public boolean isConnected(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return parent[v] == parent[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] components = new ArrayList[cccount];
        for (int i = 0; i < cccount; i++) {
            components[i] = new ArrayList<>();
        }
        for (int v = 0; v < G.V(); v++) {
            components[parent[v]].add(v);
        }
        return components;
    }

    public static void main(String[] args) {
        String filePath = ConnectedComponent.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        ConnectedComponent cc = new ConnectedComponent(graph);
        System.out.println(cc.count());
        System.out.println(cc.isConnected(0, 6));
        System.out.println(cc.isConnected(0, 5));
        ArrayList<Integer>[] components = cc.components();
        for (int i = 0; i < components.length; i++) {
            ArrayList<Integer> component = components[i];
            System.out.print(i + ": ");
            for (Integer v : component) {
                System.out.print(v + " ");
            }
            System.out.println();
        }
    }
}
